package com.linkvin.ec.hcs.service.sysadmin.impl;

import com.linkvin.ec.hcs.dao.mapper.sysadmin.PermissionMapper;
import com.linkvin.ec.hcs.dao.model.sysadmin.Permission;
import com.linkvin.ec.hcs.service.security.domains.JwtUser;
import com.linkvin.ec.hcs.service.sysadmin.PermissionService;
import com.linkvin.ec.hcs.service.util.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service
public class PermissionServiceImpl implements PermissionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PermissionServiceImpl.class);

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<Permission> getFistPermission() {

        JwtUser authUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (Objects.equals(authUser, null)) {
            throw new BaseException("账号不存在");
        }

        Integer userId = authUser.getUserId();

        List<Permission> permissionList = permissionMapper.selectPermListByUserId(userId);

        List<Permission> permissions = new ArrayList<>();
        for(Permission permission :permissionList){
            if(permission.getPid().equals(0)){
                permissions.add(permission);
            }
        }
        return permissions;
    }

    @Override
    public List<Permission> listChildPermission(Integer pid) {
        JwtUser authUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (Objects.equals(authUser, null)) {
            throw new BaseException("账号不存在");
        }

        Integer userId = authUser.getUserId();

        List<Permission> permissionList = permissionMapper.selectPermListByUserId(userId);
        List<Permission> result = new ArrayList<>();
        setSubMenu(pid,result,permissionList);
        return result;
    }

    private void setSubMenu(Integer pid, List<Permission> result, List<Permission> source) {
        for (Permission perm : source) {
            if (perm.getPid().equals(pid)) {
                result.add(perm);
                setSubMenu(perm.getId(), result, source);
            }
        }
    }

    @Override
    public List<Permission> listAllPermission(){
        return permissionMapper.selectList(null);
    }

    @Override
    public List<Permission> listPermissionByIds(List<Integer> ids){
        return  permissionMapper.selectBatchIds(ids);
    }

}
